<template>
	<view style="position: relative;">
		<!-- 顶部图片部分 -->
		<view class="header-hero">
			<u--image :showLoading="true" :src="storeImage" width="380px" height="220px"></u--image>

			<!-- 头像：压一半在大图与下方之间 -->
			<view class="avatar-overlay">
				<u--image :showLoading="true" :src="shopAvatar" width="120px" height="120px" radius="60px"></u--image>
			</view>

			<!-- 返回按钮 -->
			<view class="back-button" @click="goBack">
				<u-icon name="arrow-left" size="24" color="#fff"></u-icon>
			</view>
		</view>

		<!-- 店铺信息部分 -->
		<view class="shop-brief">
			<u-text :text="shopName" size="20px" bold="true" align="center"></u-text>
			<u-text :text="`评价${evalTotal}`" align="center" style="margin-top: 5px;"></u-text>
			<u-text text="配送费立减10元" color="blue" align="center" style="margin-top: 5px;"></u-text>
			<u-text text="温馨提示：请适量点餐" align="center" style="margin-top: 10px;"></u-text>
		</view>

		<!-- 标签页切换 -->
		<view class="tabs-bar">
			<view style="display:flex; justify-content:space-around;">
				<view v-for="(tab, index) in tabs" :key="index"
					style="display:flex; flex-direction:column; align-items:center; padding:8px;"
					:class="{ 'active': tab.isActive }" @click="switchTab(index)">
					<text style="font-size:16px;" :class="{ 'active': tab.isActive }">{{ tab.name }}</text>
					<view v-if="tab.isActive" style="width:20px; height:2px; background-color:#4cd964; margin-top:4px;">
					</view>
				</view>
			</view>
		</view>

		<!-- 分类选择 -->
		<view v-if="currentTab === '点餐'" class="menu-section">
			<view style="display: flex;">
				<!-- 左侧分类列表 -->
				<view style="width: 130px; background-color: #f8f8f8; height: 500px;">
					<view v-for="(category, index) in categories" :key="index"
						style="padding: 20px; text-align: center; border-bottom: 1px solid #eee;"
						:class="{ 'category-active': currentCategoryIndex === index }" @click="switchCategory(index)">
						<text>{{ category }}</text>
					</view>
				</view>
				<!-- 右侧商品列表 -->
				<view style="flex: 1; background-color: #fff; height: 500px; overflow-y: auto;">
					<view v-for="(item, index) in currentItems" :key="index"
						style="display: flex; padding: 10px; border-bottom: 1px solid #eee; align-items: center;"
						@click="goToDetail(item)">
						<u--image :showLoading="true" :src="item.image" width="80px" height="80px"></u--image>
						<view style="flex: 1; padding: 0 10px;">
							<u-text :text="item.name" size="16px" bold="true"></u-text>
							<u-text :text=" '￥' + item.price" color="#ff5500" style="margin-top: 5px;"></u-text>
						</view>
						<view
							style="width: 30px; height: 30px; border: 1px solid #ddd; border-radius: 50%; display: flex; align-items: center; justify-content: center;"
							@click.stop="showSpecPopup(item)">
							<view
								style="position: relative; width: 30px; height: 30px; border: 1px solid #ddd; border-radius: 50%; display: flex; align-items: center; justify-content: center;"
								@click.stop="showSpecPopup(item)">
								<text>+</text>
								<view class="item-qty-badge" v-if="getCartQtyByGoodsId(item.goodsId) > 0">
									{{ getCartQtyByGoodsId(item.goodsId) }}
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 评价部分 -->
		<view>
			<view v-if="currentTab === '评价'" class="review-wrap">
				<view v-if="evaluateList.length === 0" class="empty-review">暂无评价</view>
				<view v-else>
					<view class="review-card" v-for="(item, i) in evaluateList" :key="item.id || i">
						<view class="review-header">
							<u--image v-if="item.userAvatar" :src="item.userAvatar" width="64rpx" height="64rpx"
								radius="32rpx" :showLoading="true" />
							<view v-else class="avatar">{{ (item.userName || `用户${i+1}`).slice(0,1) }}</view>
							<view class="meta">
								<text class="name">{{ item.userName || `用户${i+1}` }}</text>
								<text class="time">{{ item.time }}</text>
							</view>
						</view>

						<view class="review-scores">
							<text class="score-badge product">商品 {{ item.goodsScore || 0 }}分</text>
							<text class="score-badge delivery">配送 {{ item.deliveryScore || 0 }}分</text>
						</view>

						<view class="review-content">{{ item.comment }}</view>
					</view>
				</view>
			</view>

			<view v-if="evaluateList.length < evalTotal" style="text-align:center;color:#999;margin:10px 0;">
				<u-button text="加载更多" size="small" @click="fetchEvaluates()" :loading="evalLoading"></u-button>
			</view>
			<view v-else-if="evaluateList.length" style="text-align:center;color:#bbb;font-size:24rpx;">没有更多了</view>
		</view>


		<!-- 商家部分 -->
		<view v-if="currentTab === '商家'" class="merchant-panel">
			<view class="merchant-card">
				<u--image :showLoading="true" :src="storeImage" width="100%" height="180px" radius="12px"></u--image>
			</view>

			<view class="info-card">
				<text class="card-title">商家信息</text>
				<view class="info-row">
					<u-icon name="phone" color="#4cd964" size="20"></u-icon>
					<text class="info-text">{{ shopDetail.shopTel || '—' }}</text>
				</view>
				<view class="info-row">
					<u-icon name="map" color="#4cd964" size="20"></u-icon>
					<text class="info-text">{{ shopDetail.shopAddress || '—' }}</text>
				</view>
				<view class="info-row">
					<u-icon name="clock" color="#4cd964" size="20"></u-icon>
					<text class="info-text">{{ (shopDetail.shopOpenTime || '') }} -
						{{ (shopDetail.shopCloseTime || '') }}</text>
				</view>
			</view>

			<view class="license-card" v-if="shopDetail.shopLicense">
				<text class="card-title">营业执照</text>
				<u--image :src="normalize(shopDetail.shopLicense)" width="100%" height="200px" radius="12px"
					:showLoading="true" />
			</view>
		</view>

		<!-- 规格选择弹窗（动态规格组） -->
		<view v-if="showSpec"
			style="position: fixed; bottom: 0; left: 0; right: 0; background-color: #fff; z-index: 1000; padding: 20px; border-radius: 20px 20px 0 0; max-height: 80vh; overflow-y: auto;">
			<view style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
				<text style="font-size: 18px; font-weight: bold;">{{ currentItem.name }}</text>
				<text @click="closeSpecPopup" style="font-size: 24px; color: #999;">×</text>
			</view>

			<text
				style="color: #ff5500; font-size: 18px; font-weight: bold; margin-bottom: 15px; display: block;">￥{{ currentSpecPrice.toFixed(2) }}</text>

			<!-- 动态规格组 -->
			<view v-for="group in specGroups" :key="group.typeId" style="margin-bottom: 20px;">
				<text style="font-weight: bold; display: block; margin-bottom: 10px;">{{ group.typeName }}</text>
				<view style="display: flex; flex-wrap: wrap; gap: 10px;">
					<view v-for="val in group.values" :key="val.id" @click="selectSpec(group.typeId, val)"
						style="padding: 8px 15px; border: 1px solid #ddd; border-radius: 20px; font-size: 14px;" :style="{
		          borderColor: isSelected(group.typeId, val) ? '#4cd964' : '#ddd',
		          color: isSelected(group.typeId, val) ? '#4cd964' : '#333',
		          background: isSelected(group.typeId, val) ? '#f0f9eb' : '#fff'
		        }">
						<text>{{ val.name }}</text>
					</view>
				</view>
			</view>

			<text style="color: #999; font-size: 12px; display: block; margin-top: 10px;">
				已选：{{ selectedSpecsText }}
			</text>

			<button @click="confirmAddToCart"
				style="background-color: #4cd964; color: #fff; border-radius: 20px; padding: 12px; width: 100%; font-size: 16px; font-weight: bold; margin-top: 20px;">
				我选好了
			</button>
		</view>

		<!-- 购物车弹窗 -->
		<view v-if="showCart"
			style="position: fixed; bottom: 0; left: 0; right: 0; background-color: #fff; z-index: 1000; padding: 20px; border-radius: 20px 20px 0 0; max-height: 60vh; overflow-y: auto;">
			<view style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
				<text style="font-size: 18px; font-weight: bold;">已选商品</text>
				<text @click="closeCart" style="font-size: 24px; color: #999;">×</text>
			</view>

			<view v-for="(item, index) in cartItems" :key="index"
				style="margin-bottom: 15px; border-bottom: 1px solid #eee; padding-bottom: 15px;">
				<view style="display: flex; justify-content: space-between; align-items: flex-start;">
					<view style="flex: 1;">
						<text style="font-weight: bold; display: block;">{{ item.name }}</text>
						<text
							style="color: #999; font-size: 12px; display: block; margin: 5px 0;">{{ item.specsSummary }}</text>
					</view>
					<text style="color: #ff5500; font-weight: bold;">¥{{ item.price }}</text>
				</view>

				<view style="display: flex; justify-content: space-between; align-items: center; margin-top: 10px;">
					<text style="color: #999; font-size: 12px;"></text>
					<view style="display: flex; align-items: center;">
						<view @click.stop="decreaseQuantity(index)"
							style="width: 28px; height: 28px; border: 1px solid #ddd; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 16px;">
							-</view>
						<text style="margin: 0 10px; min-width: 20px; text-align: center;">{{ item.quantity }}</text>
						<view @click.stop="increaseQuantity(index)"
							style="width: 28px; height: 28px; border: 1px solid #ddd; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 16px;">
							+</view>
					</view>
				</view>
			</view>

			<view style="margin-top: 15px; padding-top: 15px; border-top: 1px solid #eee;">
				<view style="display: flex; justify-content: space-between; margin-bottom: 10px;">
					<text style="font-size: 14px;">包装费</text>
					<text style="color:#ff5500">¥{{ Number(packagingFeeTotal).toFixed(2) }}</text>
				</view>

				<view style="display: flex; justify-content: space-between; margin-top: 15px;">
					<text style="font-size: 18px; font-weight: bold;">合计</text>
					<text
						style="font-size:18px;font-weight:bold;color:#ff5500">¥{{ Number(totalWithFee).toFixed(2) }}</text>
				</view>
			</view>

			<button @click="checkout"
				style="background-color: #4cd964; color: #fff; border-radius: 20px; padding: 12px; width: 100%; font-size: 16px; font-weight: bold; margin-top: 20px;">去结算</button>
		</view>


		<!-- 确认删除弹窗 -->
		<view v-if="showDeleteConfirm"
			style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0,0,0,0.5); z-index: 2000; display: flex; justify-content: center; align-items: center;">
			<view style="background-color: #fff; width: 80%; max-width: 300px; border-radius: 12px; padding: 20px;">
				<text
					style="font-size: 18px; font-weight: bold; display: block; text-align: center; margin-bottom: 20px;">确定不要这个了吗？</text>
				<view style="display: flex; justify-content: space-between; gap: 15px;">
					<button @click="cancelDelete"
						style="background-color: #f8f8f8; color: #333; border-radius: 20px; flex: 1; height: 40px; line-height: 40px; border: none;">取消</button>
					<button @click="confirmDelete"
						style="background-color: #4cd964; color: #fff; border-radius: 20px; flex: 1; height: 40px; line-height: 40px; border: none;">确定</button>
				</view>
			</view>
		</view>

		<!-- 遮罩层 -->
		<view v-if="showSpec || showCart || showDeleteConfirm" @click="closeAllPopups"
			style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0,0,0,0.5); z-index: 999;">
		</view>

		<view
			style="position: fixed; bottom: 0; left: 0; width: 100%; height: 60px; background-color: #fff; border-top: 1px solid #eee; display: flex; align-items: center; justify-content: space-between; padding: 0 15px; z-index: 998;">
			<view style="display: flex; align-items: center;" @click="openCart">
				<view style="position: relative;">
					<u-icon name="shopping-cart" size="28" color="#4cd964"></u-icon>
					<view v-if="totalQuantity > 0"
						style="position: absolute; top: -8px; right: -8px; background-color: #ff5500; width: 20px; height: 20px; border-radius: 50%; display: flex; align-items: center; justify-content: center;">
						<text style="color: #fff; font-size: 12px;">{{ totalQuantity }}</text>
					</view>
				</view>
				<text style="margin-left: 10px; font-size: 16px; font-weight: bold;">¥{{ totalPrice}}</text>
			</view>
			<button @click="checkout" :disabled="totalQuantity === 0"
				style="background-color: #4cd964; color: #fff; border-radius: 20px; height: 40px; line-height: 40px; padding: 0 30px; font-size: 16px; border: none; margin-left: 180px; "
				:style="{opacity: totalQuantity === 0 ? 0.6 : 1}">
				去结算
			</button>
		</view>


	</view>
</template>


<script>
	import {
		get
	} from '@/utils/request'
	export default {
		data() {
			return {
				shopId: null,
				shopName: '',
				shopAvatar: '',
				storeImage: '',
				specGroups: [], // [{ typeId, typeName, values:[{id,name}] }]
				selectedSpecs: {},
				showSpec: false,
				currentItem: {},

				tabs: [{
						name: "点餐",
						isActive: true
					},
					{
						name: "评价",
						isActive: false
					},
					{
						name: "商家",
						isActive: false
					}
				],
				currentTab: "点餐",
				categories: [],
				// 全量商品（后端返回）
				goods: [],
				// 当前选中的 goodsType
				currentCategoryType: '', // 用于过滤商品的真实类型值
				currentCategoryIndex: 0, // 用于样式高亮的索引
				items: [],
				// 购物车相关
				cartItems: [],
				showCart: false,

				// 删除确认
				showDeleteConfirm: false,
				deletingIndex: null,

				// 评价
				evaluateList: [],
				evalPageNum: 1,
				evalPageSize: 10,
				evalTotal: 0,
				evalLoading: false,

				// 商家详情（动态渲染用）
				shopDetail: {
					shopAddress: '',
					shopLicense: '',
					shopTel: '',
					shopOpenTime: '',
					shopCloseTime: ''
				}
			}
		},
		computed: {
			currentItems() {
				return this.goods.filter(g => g.goodsType === this.currentCategoryType)
			},

			specDeltaPrice() {
				// 选中的每个规格值的 price 求和
				return Object.values(this.selectedSpecs)
					.reduce((s, v) => s + Number(v?.price || 0), 0)
			},
			currentSpecPrice() {
				return Number(this.currentItem?.price || 0) + this.specDeltaPrice
			},
			// 商品总价
			totalPrice() {
				return this.cartItems.reduce(
					(sum, i) => sum + Number(i.price || 0) * Number(i.quantity || 0),
					0
				)
			},
			totalQuantity() {
				return this.cartItems.reduce((t, i) => t + Number(i.quantity || 0), 0)
			},
			// goodsId -> qty
			cartCountByGoodsId() {
				const map = {}
				this.cartItems.forEach(i => {
					const id = i.goodsId || i.goods_id
					if (!id) return
					map[id] = (map[id] || 0) + Number(i.quantity || 0)
				})
				return map
			},
			// 包装费总额（按件计费）
			packagingFeeTotal() {
				return this.cartItems.reduce(
					(sum, i) => sum + (parseFloat(i.packagingFee) || 0) * Number(i.quantity || 0),
					0
				)
			},
			// 合计
			totalWithFee() {
				return this.totalPrice + this.packagingFeeTotal
			},
			selectedSpecsText() {
				return this.specGroups
					.map(g => `${g.typeName}:${this.selectedSpecs[g.typeId]?.name || ''}`)
					.filter(s => !s.endsWith(':'))
					.join(' / ')
			}

		},
		onLoad(options) {
			this.shopId = options?.id
			if (!this.shopId) {
				uni.showToast({
					icon: 'none',
					title: '缺少商家ID'
				})
				return
			}
			// console.log(this.shopId);
			this.fetchShop()
			this.fetchGoods()
			this.fetchEvaluateTotal()
		},
		methods: {
			//获取评价总条数
			async fetchEvaluateTotal() {
				try {
					const res = await get('/order/evaluate/list', {
						pageNum: 1,
						pageSize: 1,
						shopId: this.shopId
					})
					this.evalTotal = res?.total ?? (Array.isArray(res?.rows) ? res.rows.length : 0)
				} catch (e) {
					this.evalTotal = 0
				}
			},
			// 统一图片地址
			normalize(u) {
				if (!u) return ''
				if (/^https?:\/\//i.test(u)) return u
				const FILE_BASE = (process.env.VUE_APP_FILE_BASE || process.env.VUE_APP_BASE_API || '').replace(/\/$/, '')
				return `${FILE_BASE}${u.startsWith('/') ? '' : '/'}${u}`
			},
			async fetchShop() {
				const res = await get(`/order/shop/${this.shopId}`)
				// console.log(res);
				const data = res?.data || res
				this.shopName = data.shopName || ''
				this.shopAvatar = this.normalize(data.shopAvatar || data.shopPhoto)
				this.storeImage = this.normalize(data.shopPhoto || data.shopBanner || this.shopAvatar)
				this.shopAddress = data.shopAddress
				this.shopLicense = data.shopLicense
				this.shopTel = data.shopTel
				this.shopOpenTime = data.shopOpenTime
				this.shopCloseTime = data.shopCloseTime
			},

			applyShopToDetail() {
				this.shopDetail = {
					shopAddress: this.shopAddress || (this.shop?.shopAddress) || '',
					shopLicense: this.shopLicense || (this.shop?.shopLicense) || '',
					shopTel: this.shopTel || (this.shop?.shopTel) || '',
					shopOpenTime: this.shopOpenTime || (this.shop?.shopOpenTime) || '',
					shopCloseTime: this.shopCloseTime || (this.shop?.shopCloseTime) || ''
				}
			},

			async fetchGoods() {
				const res = await get('/order/goods/list', {
					pageNum: 1,
					pageSize: 500,
					shopId: this.shopId
				})
				const rows = Array.isArray(res?.rows) ? res.rows : (Array.isArray(res) ? res : [])
				const types = []
				rows.forEach(r => {
					if (r.goodsType && !types.includes(r.goodsType)) types.push(r.goodsType)
				})
				this.categories = types
				this.currentCategoryIndex = 0
				this.currentCategoryType = types[0] || ''
				this.goods = rows.map(r => ({
					goodsId: r.goodsId,
					goodsType: r.goodsType,
					name: r.goodsName,
					price: r.price ?? r.goodsPrice ?? 0,
					image: this.normalize(r.goodsImage || r.image || r.picUrl),
					packagingFee: Number(r.goodsPackage ?? r.goodsPackage ?? r.boxFee ?? 0)
				}))
			},

			// 分类切换：用类型值而不是索引
			switchCategory(index) {
				this.currentCategoryIndex = index
				this.currentCategoryType = this.categories[index]
			},

			// 返回
			goBack() {
				uni.navigateBack()
			},

			// 规格选择相关方法
			// 将 showSpecPopup 改为 async
			async showSpecPopup(item) {
				this.currentItem = {
					...item,
					packagingFee: Number(item.packagingFee) || 0
				}
				await this.loadSpecsForItem(item.goodsType)
				this.selectedSpecs = {}
				this.specGroups.forEach(g => {
					if (g.values?.length) this.$set(this.selectedSpecs, g.typeId, g.values[0])
				})
				this.showSpec = true
			},

			async loadSpecsForItem(goodsType) {
				try {
					const typeRes = await get('/order/sort/list', {
						pageNum: 1,
						pageSize: 1,
						goodsType
					})
					const goodsTypeId = typeRes?.rows?.[0]?.goodsTypeId ?? typeRes?.rows?.[0]?.id
					if (!goodsTypeId) {
						this.specGroups = [];
						return
					}
					// console.log(goodsTypeId);  1
					//根据goodsTypeId 得到 spec_type_id集合
					const specRes = await get('/order/spec/list', {
						pageNum: 1,
						pageSize: 9999,
						goodsTypeId
					})
					const rows = Array.isArray(specRes?.rows) ? specRes.rows : []
					// console.log(rows); 正确
					const specTypeIds = [...new Set(rows.map(r => r.specTypesId || r.spec_types_id).filter(Boolean))]
					// console.log(specTypeIds);  1 2 3 4
					const groups = await Promise.all(specTypeIds.map(async (specTypesId) => {
						const typeInfoRes = await get(`/order/types/${specTypesId}`)
						// console.log(typeInfoRes.data); 正确
						const typeInfo = typeInfoRes?.data || typeInfoRes
						const typeName = typeInfo.specTypesName || typeInfo.typeName ||
							`规格(${specTypesId})`
						// console.log(typeName); 加料 分量 甜度 温度

						// 按 specTypesId 查询值列表
						const valsRes = await get('/order/values/list', {
							pageNum: 1,
							pageSize: 9999,
							specTypesId // 注意字段名与后端实体一致，可能是 specTypesId/spec_types_id
						})
						// console.log(valsRes); 正确
						const valRows =
							Array.isArray(valsRes?.rows) ? valsRes.rows :
							Array.isArray(valsRes?.data) ? valsRes.data : []
						// console.log(valRows); ✔
						const values = valRows.map(v => ({
							id: v.specValuesId || v.spec_values_id || v.id,
							name: v.specValues || v.spec_value || v.value || v.name,
							price: Number(v.specValuesPrice || v.spec_values_price || v
								.price || 0) // 关键：规格加价
						})).filter(x => x.id && x.name)
						// console.log(values);
						return {
							typeId: specTypesId,
							typeName,
							values
						}
					}))
					this.specGroups = groups.filter(g => g.values?.length)
				} catch (e) {
					console.error('loadSpecsForItem error:', e)
					this.specGroups = []
					uni.showToast({
						icon: 'none',
						title: '规格加载失败'
					})
				}
			},

			isSelected(typeId, val) {
				return this.selectedSpecs[typeId]?.id === val.id
			},
			selectSpec(typeId, val) {
				this.$set(this.selectedSpecs, typeId, val)
			},
			closeSpecPopup() {
				this.showSpec = false;
			},
			selectSize(size) {
				this.selectedSize = size;
			},
			selectTemp(temp) {
				this.selectedTemp = temp;
			},
			selectSweet(sweet) {
				this.selectedSweet = sweet;
			},

			// 添加到购物车
			confirmAddToCart() {
				if (!this.currentItem.name) {
					uni.showToast({
						title: '请选择商品',
						icon: 'none'
					})
					return
				}
				const specsSummary = this.selectedSpecsText
				const specsMap = JSON.parse(JSON.stringify(this.selectedSpecs))

				const newItem = {
					...this.currentItem,
					goodsId: this.currentItem.goodsId, // 关键：带上ID
					quantity: 1,
					price: Number(this.currentSpecPrice),
					packagingFee: Number(this.currentItem.packagingFee) || 0,
					specsSummary,
					specsMap
				}
				const idx = this.cartItems.findIndex(i => i.name === newItem.name && i.specsSummary ===
					newItem
					.specsSummary)
				if (idx >= 0) this.cartItems[idx].quantity += 1
				else this.cartItems.push(newItem)

				uni.showToast({
					title: '已添加到购物车',
					icon: 'success'
				})
				this.closeSpecPopup()
			},
			getCartQtyByGoodsId(goodsId) {
				return this.cartCountByGoodsId[goodsId] || 0
			},

			// 购物车相关方法
			openCart() {
				if (this.cartItems.length > 0) {
					this.showCart = true;
				} else {
					uni.showToast({
						title: '购物车为空',
						icon: 'none'
					});
				}
			},

			// 关闭购物车
			closeCart() {
				this.showCart = false;
			},

			// 增加数量
			increaseQuantity(index) {
				this.cartItems[index].quantity += 1;
			},

			// 减少数量
			decreaseQuantity(index) {
				if (this.cartItems[index].quantity > 1) {
					this.cartItems[index].quantity -= 1;
				} else {
					this.showDeleteConfirm = true;
					this.deletingIndex = index;
				}
			},

			// 取消删除
			cancelDelete() {
				this.showDeleteConfirm = false;
				this.deletingIndex = null;
			},

			// 确认删除
			confirmDelete() {
				if (this.deletingIndex !== null) {
					this.cartItems.splice(this.deletingIndex, 1);
					uni.showToast({
						title: '已移除商品',
						icon: 'success'
					});
				}
				this.showDeleteConfirm = false;
				this.deletingIndex = null;

				if (this.cartItems.length === 0) {
					this.showCart = false;
				}
			},

			// 结算
			// 去结算
			checkout() {
				if (this.cartItems.length === 0) {
					uni.showToast({
						title: '购物车为空',
						icon: 'none'
					})
					return
				}

				const payload = {
					shopId: this.shopId,
					shopName: this.shopName,
					items: this.cartItems.map(i => ({
						goodsId: i.goodsId,
						name: i.name,
						image: i.image,
						price: Number(i.price) || 0,
						quantity: Number(i.quantity) || 0,
						packagingFee: Number(i.packagingFee) || 0,
						specsSummary: i.specsSummary || '',
						amount: (Number(i.price) || 0) * (Number(i.quantity) || 0),
						packagingFeeAmount: (Number(i.packagingFee) || 0) * (Number(i.quantity) || 0)
					})),
					totals: {
						itemsTotal: Number(this.totalPrice) || 0,
						packagingFeeTotal: Number(this.packagingFeeTotal) || 0,
						payable: Number(this.totalWithFee) || 0
					}
				}

				//输出测试
				// console.log('checkout payload:', JSON.parse(JSON.stringify(payload)))

				// uni.showModal({
				// 	title: '调试-订单数据',
				// 	content: JSON.stringify(payload, null, 2).slice(0, 1000), // 防止过长
				// 	showCancel: false
				// })

				// 兜底存储（小程序某些场景下无法取到 eventChannel）
				uni.setStorageSync('checkoutData', payload)

				uni.navigateTo({
					url: '/pages/ConfirmOrder/ConfirmOrder',
					success: res => {
						res.eventChannel && res.eventChannel.emit('checkoutData', payload)
					}
				})
			},

			// 关闭所有弹窗
			closeAllPopups() {
				this.showSpec = false;
				this.showCart = false;
				this.showDeleteConfirm = false;
			},

			goToDetail(item) {
				uni.navigateTo({
					url: `/pages/goodDetail/goodDetail?name=${item.name}&price=${item.price}&image=${item.image}`
				});
			},

			switchTab(index) {
				this.tabs.forEach((t, i) => (t.isActive = i === index))
				this.currentTab = this.tabs[index].name
				if (this.currentTab === '评价' && this.evaluateList.length === 0) {
					this.fetchEvaluates(true)
				}
				if (this.currentTab === '商家' && !this.shopDetail.shopAddress) {
					this.applyShopToDetail()
				}
			},
			//评论展示及相关用户信息
			async fetchEvaluates(reset = false) {
				if (this.evalLoading) return
				if (reset) {
					this.evalPageNum = 1;
					this.evaluateList = []
				}
				this.evalLoading = true
				try {
					const res = await get('/order/evaluate/list', {
						pageNum: this.evalPageNum,
						pageSize: this.evalPageSize,
						shopId: this.shopId
					})
					const rows = Array.isArray(res?.rows) ? res.rows : []
					this.evalTotal = res?.total ?? rows.length

					const ids = [...new Set(rows.map(r => r.userId || r.user_id).filter(Boolean))]
					const userMap = {}
					await Promise.all(ids.map(async id => {
						try {
							const ures = await get(`/order/frontUser/${id}`)
							const u = ures?.data || ures || {}
							console.log(u);
							userMap[id] = {
								name: u.nickName || u.userName || `用户${id}`,
								avatar: u.avatar ? this.normalize(u.avatar) : ''
							}
						} catch (_) {
							userMap[id] = {
								name: `用户${id}`,
								avatar: ''
							}
						}
					}))

					const merged = rows.map(r => {
						const uid = r.userId || r.user_id
						const u = userMap[uid] || {}
						return {
							id: r.evaluateId || r.evaluate_id || r.id,
							userName: u.name || r.userName || `用户${uid || ''}`,
							userAvatar: u.avatar || '',
							goodsScore: r.evaluateGoodsSco || r.evaluate_goods_sco || 0,
							deliveryScore: r.evaluateDeliverySco || r.evaluate_delivery_sco || 0,
							comment: r.evaluateComment || r.evaluate_comment || '',
							time: r.evaluateTime || r.evaluate_time || '',
							reply: r.evaluateRelayComm || r.evaluate_relay_comm || '',
							replyTime: r.evaluateRelayTime || r.evaluate_relay_time || ''
						}
					})
					this.evaluateList = this.evaluateList.concat(merged)
					this.evalPageNum += 1
				} finally {
					this.evalLoading = false
				}
			},

			onReachBottom() {
				if (this.currentTab === '评价' && this.evaluateList.length < this.evalTotal) {
					this.fetchEvaluates()
				}
			}
		},
	}
</script>

<style>
	.back-button {
		position: absolute;
		top: 20rpx;
		left: 20rpx;
		width: 80rpx;
		height: 80rpx;
		background-color: rgba(0, 0, 0, 0.5);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 2;
	}

	.back-button:active {
		background-color: rgba(0, 0, 0, 0.7);
	}

	.active {
		color: #4cd964;
	}

	.category-active {
		background-color: #fff;
		color: #4cd964;
		font-weight: 700;
		border-left: 6rpx solid #4cd964;
	}

	.item-qty-badge {
		position: absolute;
		top: -8rpx;
		right: -8rpx;
		min-width: 24rpx;
		height: 24rpx;
		padding: 0 6rpx;
		background-color: #ff5500;
		color: #fff;
		border-radius: 9999rpx;
		font-size: 20rpx;
		line-height: 24rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	/* scoped */
	.review-wrap {
		padding: 20rpx 24rpx 120rpx;
		background: #fafafa;
	}

	.review-card {
		background: #fff;
		border-radius: 16rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, .05);
	}

	.review-header {
		display: flex;
		align-items: center;
	}

	.avatar {
		width: 64rpx;
		height: 64rpx;
		border-radius: 50%;
		background: #4cd964;
		color: #fff;
		display: flex;
		align-items: center;
		justify-content: center;
		font-weight: 700;
	}

	.meta {
		margin-left: 16rpx;
		display: flex;
		flex-direction: column;
		gap: 6rpx;
	}

	.name {
		font-size: 28rpx;
		font-weight: 700;
		color: #333;
	}

	.time {
		font-size: 22rpx;
		color: #999;
	}

	.review-scores {
		margin: 12rpx 0 8rpx;
		display: flex;
		gap: 12rpx;
	}

	.score-badge {
		padding: 4rpx 10rpx;
		border-radius: 999rpx;
		font-size: 22rpx;
	}

	.score-badge.product {
		background: #fff4e6;
		color: #ff8a00;
	}

	.score-badge.delivery {
		background: #e8f6ff;
		color: #1296db;
	}

	.review-content {
		line-height: 1.7;
		font-size: 26rpx;
		color: #444;
	}

	.empty-review {
		text-align: center;
		color: #999;
		padding: 60rpx 0;
	}

	.shop-brief {
		background: #fff;
		margin-top: 12rpx;
		padding: 16rpx;
		text-align: center;
		border-radius: 12rpx;
	}

	.tabs-bar {
		position: sticky;
		/* 小程序/H5 均可用 */
		top: 0;
		z-index: 10;
		background: #fff;
		padding: 10rpx 0;
		margin-top: 12rpx;
		border-bottom: 1px solid #f2f2f2;
	}

	.menu-section {
		margin-top: 12rpx;
		position: relative;
		/* 取消 absolute */
	}

	.review-wrap {
		margin-top: 12rpx;
	}

	.header-hero {
		position: relative;
	}

	.avatar-overlay {
		position: absolute;
		left: 50%;
		bottom: -60px;
		/* 压一半（头像高120px的一半） */
		transform: translateX(-50%);
		z-index: 5;
		width: 120px;
		height: 120px;
		border-radius: 60px;
		background: #fff;
		/* 白色描边圈 */
		padding: 4px;
		box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, .08);
	}

	.shop-brief {
		margin-top: 80px;
	}

	.merchant-panel {
		padding: 16rpx;
		background: #fafafa;
	}

	.merchant-card {
		background: #fff;
		border-radius: 12rpx;
		padding: 12rpx;
		box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, .05);
	}

	.info-card,
	.license-card {
		background: #fff;
		border-radius: 12rpx;
		padding: 16rpx;
		margin-top: 16rpx;
		box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, .05);
	}

	.card-title {
		font-weight: 700;
		color: #333;
		font-size: 28rpx;
	}

	.info-row {
		display: flex;
		align-items: center;
		gap: 12rpx;
		padding: 12rpx 0;
		border-bottom: 1px solid #f5f5f5;
	}

	.info-row:last-child {
		border-bottom: none;
	}

	.info-text {
		color: #333;
		font-size: 26rpx;
		flex: 1;
	}
</style>